package com.zeroone.star.sample.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zeroone.star.project.dto.PageDTO;
import com.zeroone.star.project.dto.sample.SampleDTO;
import com.zeroone.star.project.query.sample.SampleQuery;
import com.zeroone.star.sample.entity.Sample;
import com.zeroone.star.sample.mapper.SampleMapper;
import com.zeroone.star.sample.service.ISampleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zeroone.star.sample.service.SeataFeignService;
import io.seata.spring.annotation.GlobalTransactional;
import org.mapstruct.Mapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 * 员工表 服务实现类
 * </p>
 *
 * @author lyx
 * @since 2024-10-29
 */

@Mapper(componentModel = "spring")
interface MsSampleMapper {
    /**
     * 将 Sample do转换为dto
     * @param sample do对象
     * @return 转换结果
     */
    SampleDTO sample2SampleDTO(Sample sample);
}

@Service
public class SampleServiceImpl extends ServiceImpl<SampleMapper, Sample> implements ISampleService {

    @Resource
    MsSampleMapper msSampleMapper;

    @Override
    public PageDTO<SampleDTO> listAll(SampleQuery query) {
        // 构建分页对象
        Page<Sample> page = new Page<>(query.getPageIndex(), query.getPageSize());
        // 构建查询条件
        QueryWrapper<Sample> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", query.getName());
        // 执行查询
        Page<Sample> result = baseMapper.selectPage(page, queryWrapper);
        // 转换结果
        return PageDTO.create(result, msSampleMapper::sample2SampleDTO);
    }


    @Override
    public SampleDTO getById(Integer id) {
        Sample result = baseMapper.selectById(id);
        if (result != null) {
            return msSampleMapper.sample2SampleDTO(result);
        }
        return null;
    }


    @Resource
    SeataFeignService seata;

    @GlobalTransactional
    @Override
    public int testSeata() {
        //先执行本服务逻辑
        Sample sample = new Sample();
        sample.setName("测试事务");
        sample.setAge(3);
        sample.setSex("男");
        int row = baseMapper.insert(sample);
        if (row != 1){
            throw new RuntimeException("当前服务保存失败");
        }

        //再执行远程服务
        Integer integer = seata.testSave();
        if (integer == null || integer != 1){
            throw new RuntimeException("远程服务保存失败");
        }
        return 1;
    }
}
